package com.atguigu.gmall.common.service;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author mqx
 * @date 2020-11-20 14:21:48
 */
@Service
public class RabbitService {

    //  获取rabbitTemplate
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 主要发送消息
     * @param exchange  交换机
     * @param routingKey    路由键
     * @param message   发送消息的主体
     * @return
     */
    public boolean sendMessage(String exchange, String routingKey, Object message){
        //  调用发送方法
        //  rabbitTemplate.sendAndReceive();    有返回值
        rabbitTemplate.convertAndSend(exchange,routingKey,message);
        return true;
    }

    /**
     * 发送延迟消息的方法
     * @param exchange  交换机
     * @param routingKey    路由键
     * @param message   消息
     * @param delayTime 延迟时间
     * @return
     */
    public boolean sendDelayMessage(String exchange, String routingKey, Object message, int delayTime){

        rabbitTemplate.convertAndSend(exchange, routingKey, message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //  设置延迟时间
                message.getMessageProperties().setDelay(delayTime*1000);
                return message;
            }
        });
        return true;
    }
}
